<template>
  <div class="page-card dhData">
    <!-- <h-query :showKey="[]" :query="query" @search="search">
      <div class="a-button-right">
        <a-space>
          <UploadExcel download="/web/Enforcement/write_Enforcement" @change="$refs.htable.refresh(true)" />
          <a-button type="primary" @click="actions">抽 签</a-button>
          <a-button type="primary" @click="showHistoryAct">抽签历史记录</a-button>
          <a-button type="primary" @click="add">添 加</a-button>
        </a-space>
      </div>
    </h-query> -->
    <div style="text-align: right">
      <a-button type="primary" @click="actions">新建抽签</a-button>
    </div>

    <br>
    <div style="margin: 8px 0;">
      已选择对象：
      <a-tag closable @close="deleteUser(item)" v-for="(item, i) in selectedRow" :key="i">{{ item.name }}</a-tag>
    </div>
    <br>
    <h-table
      ref="htable"
      @init="getList"
      :config="config"
      :showHeadBgNone="true"
      showRowSelection
      @select="select"
      :zebraStripes="true">
      <span slot="type" slot-scope="{text}">
        {{ type[text] }}
      </span>
      <span slot="action" slot-scope="{text, record}">
        <a @click="look(record)">详情</a>
        <a-divider type="vertical"></a-divider>
        <a @click="edit(record)">编辑</a>
        <a-divider type="vertical"></a-divider>

        <a @click="remove(record)" class="red">删除</a>
      </span>
      <!-- <span slot="isHome" slot-scope="{text, record}">
        <a-switch v-model="record.isHome" @change="showHome(record)"></a-switch>
      </span>
      <span slot="isIndex" slot-scope="{text, record}">
        <a-switch v-model="record.isIndex" @change="showTop(record)"></a-switch>
      </span> -->
    </h-table>
    <br>
    <p>历史抽签人员：</p>
    <h-table
      ref="htable2"
      :config="config2">
    </h-table>
    <br>

    <div style="text-align: right;margin-top: 24px">
      <a-button type="primary" @click="save(1)">暂存抽签结果</a-button>
      <a-button type="danger" @click="save2()" style="margin-left: 12px">确定并存档</a-button>
    </div>

    <createInfo ref="modal" v-model="show" @submit="submit" />

    <a-modal title="抽签" v-model="showCq" width="900px" class="custom-modal">
      <a-form-model ref="ruleForm" :model="form" :labelCol="{span: 9 }" :wrapperCol="{span: 15}" :rules="rules">
        <!-- <a-form-model-item label="状态" prop="examine">
        <a-select v-model="form.examine">
          <a-select-option value="0">未审核</a-select-option>
          <a-select-option value="1">已通过</a-select-option>
          <a-select-option value="2">未通过</a-select-option>
        </a-select>
      </a-form-model-item> -->
        <a-row>
          <a-col :span="24">
            <a-form-model-item class="orientation-form" :labelCol="{span: 4}" :wrapperCol="{span: 16}" label="专家定位" prop="orientation">
              <!-- 系统建设、科学研究、指导咨询、评估论证、教育培训、应急保障、技术检查 -->
              <!-- <a-radio-group v-model="form.orientation" button-style="solid">
                <a-radio-button value="系统建设">
                  系统建设
                </a-radio-button>
                <a-radio-button value="科学研究">
                  科学研究
                </a-radio-button>
                <a-radio-button value="指导咨询">
                  指导咨询
                </a-radio-button>
                <a-radio-button value="评估论证">
                  评估论证
                </a-radio-button>
                <a-radio-button value="教育培训">
                  教育培训
                </a-radio-button>
                <a-radio-button value="应急保障">
                  应急保障
                </a-radio-button>
                <a-radio-button value="技术检查">
                  技术检查
                </a-radio-button>
              </a-radio-group> -->

              <a-checkbox-group v-model="form.orientation">
                <a-checkbox value="系统建设">
                  系统建设
                </a-checkbox>
                <a-checkbox value="科学研究">
                  科学研究
                </a-checkbox>
                <a-checkbox value="指导咨询">
                  指导咨询
                </a-checkbox>
                <a-checkbox value="评估论证">
                  评估论证
                </a-checkbox>
                <a-checkbox value="教育培训">
                  教育培训
                </a-checkbox>
                <a-checkbox value="应急保障">
                  应急保障
                </a-checkbox>
                <a-checkbox value="技术检查">
                  技术检查
                </a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>

          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="专家类型" prop="type">
              <a-select v-model="form.type" placeholder="请选择专家类型">
                <a-select-option value="0">网络专家</a-select-option>
                <a-select-option value="1">司法专家</a-select-option>
                <a-select-option value="2">行政专家</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="市级区域" prop="address">
              <a-select v-model="form.address" placeholder="请选择市级区域">
                <a-select-option v-for="item in address" :value="item.title" :key="item.title">{{ item.title }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="请输入抽签人数" prop="sum" :labelCol="{span: 12 }" :wrapperCol="{span: 12}" >
              <a-input-number style="width: 80%" v-model="form.sum" placeholder="请输入人数"></a-input-number>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="">
              <a-button type="primary" @click="submitCq" style="margin-left: 0px">开始摇号</a-button>
              <!-- <a-button type="primary" @click="writeRamOut" style="margin-left: 12px">导出</a-button> -->
            </a-form-model-item>

          </a-col>
        </a-row>

        <h-table
          ref="htable2"
          :config="config3">

        </h-table>

      </a-form-model>
      <!-- <template slot="closeIcon">
        <div @click.stop="showHistoryAct">
          抽签历史 <a-icon style="font-size: 14px" type="right" />
        </div>
      </template> -->
      <template slot="footer">
        <a-button type="primary" @click="showCq = false;saveList()">确定</a-button>
      </template>
    </a-modal>
    <a-modal title="抽签历史记录" width="800px" v-model="showHistory" @ok="showHistory=false">
      <h-table
        ref="htable2"
        @init="getListHistory"
        :config="config2">
        <span slot="action" slot-scope="{text, record}">
          <a @click="showDetail(record)">查看详情</a>
        </span>
      </h-table>
    </a-modal>
    <a-modal title="抽签历史记录" width="800px" v-model="showHistoryDetail">
      <p>专家定位：{{ detailForm.orientation }} 抽签时间：{{ detailForm.createTime }} <span style="margin: 0 10px"></span> 抽签人数：{{ detailForm.sum }}</p>
      <h-table
        ref="htable3"
        @init="getListHistoryDetail"
        :config="config3">
      </h-table>
      <template slot="footer">
        <a-button key="back" @click="showHistoryDetail = false">
          确定
        </a-button>
      </template>
    </a-modal>

    <a-modal title="保存抽签结果" width="800px" v-model="showSave">
      <p>抽签描述：</p>
      <a-textarea v-model="describe" placeholder="请输入抽签描述"></a-textarea>
      <br>
      <br>
      <h-table
        v-if="showSave"
        ref="htable3"
        :config="config3">
      </h-table>
      <template slot="footer">
        <a-button type="primary" key="back" @click="updateDescribe">
          确定
        </a-button>
      </template>
    </a-modal>

    <readInfo :id="id" v-model="showRead" />

  </div>
</template>
<script>
// eslint-disable-next-line
import { getEnforcement, getEnforcementDetail, addEnforcement, deleteEnforcement, editEnforcement, getEnforcementHistoryById, getEnforcementHistory, getEnforcementRandom, writeRamOut, getEnforcementPossession } from '@/api/db';
import createInfo from './action/createInfo';
// eslint-disable-next-line no-unused-vars
import { addEnforcementRandom, updateDescribe, getAllPossession } from '@/api/serve';
import UploadExcel from '@/components/UploadExcel/Index';
import readInfo from './action/readInfo';
import moment from 'moment';

export default {
  components: {
    createInfo,
    UploadExcel,
    readInfo
  },
  data() {
    return {
      id: '',
      // selectedRow: [],
      showCq: false,
      showHistory: false,
      showHistoryDetail: false,
      formCq: {},
      detailForm: {},
      showRead: false,
      showSave: false,
      lotteryId: '',
      describe: '',
      address: [],
      config: {
        rowKey: 'id',
        bordered: true,
        dataSource: [],

        columns: [
          {
            align: 'center',
            title: '序号',
            dataIndex: 'index',
            scopedSlots: { customRender: 'order' }
          },
          {
            align: 'center',
            title: '姓名',
            dataIndex: 'name',
            width: 300
          },
          // {
          //   align: 'center',
          //   title: '出生日期',
          //   dataIndex: 'birthday'
          // },
          {
            align: 'center',
            title: '单位',
            dataIndex: 'company'
          },
          {
            align: 'center',
            title: '职务',
            dataIndex: 'post'
          },
          {
            align: 'center',
            title: '职称',
            dataIndex: 'title'
          }
          // {
          //   align: 'center',
          //   title: '手机',
          //   dataIndex: 'phone'
          //   // width: 300
          // }
          // {
          //   align: 'center',
          //   title: '操作',
          //   dataIndex: 'action',
          //   scopedSlots: { customRender: 'action' }
          // }
        ],
        pagination: false
      },
      config2: {
        rowKey: 'id',
        bordered: true,
        dataSource: [],
        scroll: {
          y: 400
        },
        columns: [
          {
            align: 'center',
            title: '序号',
            dataIndex: 'order'
          },
          {
            align: 'center',
            title: '姓名',
            dataIndex: 'name',
            width: 300
          },
          // {
          //   align: 'center',
          //   title: '出生日期',
          //   dataIndex: 'birthday'
          // },
          {
            align: 'center',
            title: '单位',
            dataIndex: 'company'
          },
          {
            align: 'center',
            title: '职务',
            dataIndex: 'post'
          },
          {
            align: 'center',
            title: '职称',
            dataIndex: 'title'
          }
        ],
        pagination: false
      },
      config3: {
        rowKey: 'id',
        bordered: true,
        dataSource: [],
        scroll: {
          y: 400
        },
        columns: [
          {
            align: 'center',
            title: '序号',
            dataIndex: 'order'
          },
          {
            align: 'center',
            title: '姓名',
            dataIndex: 'name'
          },
          {
            align: 'center',
            title: '单位',
            dataIndex: 'company'
          },
          {
            align: 'center',
            title: '职务',
            dataIndex: 'post'
          },
          {
            align: 'center',
            title: '职称',
            dataIndex: 'title'
          },
          {
            align: 'center',
            title: '资历',
            dataIndex: 'qualifications'
          },
          {
            align: 'center',
            title: '参与项目',
            dataIndex: 'project'
          },
          {
            align: 'center',
            title: '手机号',
            dataIndex: 'phone'
          }
        ],
        pagination: false
      },
      form: {

      },
      rules: {
        sum: [{ required: true, message: '请输入' }],
        examine: [{ required: true, message: '请选择' }],
        type: [{ required: true, message: '请选择' }],
        orientation: [{ required: true, message: '请选择' }]
      },
      type: {
        0: '个人',
        1: '企业'
      },
      query: [
        {
          key: 'name',
          type: 'input',
          label: '姓名'
        }
      ],
      selectedRowKeys: [],
      selectedRow: [],
      show: false,
      queryParams: {
        pageNo: 1,
        pageSize: 10
      }
    };
  },
  created() {
    this.lotteryId = this.$route.query.id;
    const { sum, createTime } = this.$route.query;
    this.detailForm = { lotteryId: this.lotteryId, sum, createTime };
    this.getListHistoryDetail();
    this.getAddress();
  },
  methods: {
    showDetail({ lotteryId, sum, createTime }) {
      this.showHistoryDetail = true;
      this.detailForm = { lotteryId, sum, createTime };
      this.$nextTick(() => {
        this.$refs.htable3.refresh();
      });
    },
    getAddress() {
      getEnforcementPossession().then(res => {
        this.address = res.data;
      });
    },
    save(type) {
      if (!this.selectedRow.length) {
        this.$message.error('请选择！');
        return;
      }
      addEnforcementRandom({
        dataList: this.selectedRow,
        lotteryId: this.lotteryId,
        type
      }).then(res => {
        this.$message.success('暂存成功！');
      });
      // this.config3.dataSource = this.selectedRow;
    },
    save2() {
      this.config3.dataSource = this.config2.dataSource.concat(this.selectedRow);
      this.config3.dataSource = this.config3.dataSource.map((e, i) => {
        return {
          ...e,
          order: i + 1
        };
      });
      if (!this.config3.dataSource) {
        this.$message.error('请选择！');
        return;
      }

      console.log(this.config3, this.selectedRow);
      this.showSave = true;
    },
    updateDescribe() {
      if (!this.selectedRow.length) {
        this.$message.error('请选择！');
        return;
      }
      addEnforcementRandom({
        dataList: this.selectedRow,
        lotteryId: this.lotteryId,
        describe: this.describe,
        type: 2
      }).then(res => {
        this.showSave = false;
        this.$message.success('保存成功');
      });
    },

    getList(params) {
      this.config.dataSource = [];
      // // const { current, pageSize } = params;
      // Object.assign(this.queryParams, params);
      // getEnforcement(this.queryParams).then(res => {
      //   this.config.dataSource = res.data.records.map(e => {
      //     return {
      //       ...e
      //     };
      //   });
      //   this.config.pagination.total = res.data.total;
      // });
    },
    writeRamOut() {
      writeRamOut({
        writeRamOut: this.config3.dataSource
      }).then(res => {
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' });

        const filename = `${moment().format('YYYYMMDDHHmmss')}.xls`;

        if (window.navigator.msSaveOrOpenBlob) { // 兼容IE10
            navigator.msSaveBlob(blob, filename);
        } else {
          // 创建一个超链接，将文件流赋进去，然后实现这个超链接的单击事件
          const elink = document.createElement('a');
          elink.download = filename;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        }
      });
      // this.config3.dataSource
    },
    search(params) {
      Object.assign(this.queryParams, params);
      this.$refs.htable.refresh();
    },
    add() {
      this.$refs.modal.add();
      this.show = true;
    },
    edit(row) {
      this.$refs.modal.edit(row);
      this.show = true;
    },
    look({ id }) {
      this.id = id;
      this.showRead = true;
    },
    submit() {
      this.$refs.htable.refresh();
    },
    remove({ id }) {
      const that = this;
      this.$confirm({
        title: '确定要删除吗？',
        onOk() {
          deleteEnforcement({ id, isDelete: -1 }).then(res => {
            that.$message.success('删除成功');
            that.$refs.htable.refresh(true);
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },
    select({ selectedRowKeys, selectedRow }) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRow = selectedRow;
      // this.selectedRow = this.dataAll.filter(e => selectedRowKeys.includes(e.id));
    },
    deleteUser({ id }) {
      const indexs = this.selectedRow.findIndex(e => e.id == id);
      console.log('[indexs]', indexs);
      if (indexs > -1) {
        this.selectedRow.splice(indexs, 1);
        this.selectedRowKeys.splice(indexs, 1);
        console.log('[update departId]', this.departId);
        // this.$refs.htable.selectedRowKeys.splice(indexs, 1);
        this.$refs.htable.update(this.selectedRowKeys);
      }
    },
    submitCq() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          getEnforcementRandom({ ...this.form, orientation: this.form.orientation.join(','), examine: 1 }).then(res => {
            this.$message.success('抽签完成！');
            // this.show = false
            // this.$refs.htable.refresh();
            this.config3.dataSource = res.data.map((e, i) => {
              return {
                ...e,
                order: i + 1
              };
            }).filter(e => {
              console.log(this.config2.dataSource, e.name);
              return !this.config2.dataSource.map(m => m.name).includes(e.name);
            });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    saveList() {
      console.log('svaeList');
      this.config.dataSource = this.config3.dataSource;
    },
    actions() {
      this.showCq = true;
    },
    showHistoryAct() {
      // this.showHistory = true;
      // this.$nextTick(() => {
      //   this.$refs.htable2.refresh();
      // });
      this.$router.push('/db/Enforcement/history');
    },
    getListHistory(params) {
      Object.assign(this.queryParams, params);
      getEnforcementHistory(this.queryParams).then(res => {
        this.config2.dataSource = res.data.map((e, i) => {
          return {
            ...e,
            order: i + 1
          };
        });
        // this.config.pagination.total = res.data.total;
      });
    },
    getListHistoryDetail(params) {
      getEnforcementHistoryById(this.detailForm).then(res => {
        this.config2.dataSource = res.data.map((e, i) => {
          return {
            ...e,
            order: i + 1
          };
        });
        // this.config.pagination.total = res.data.total;
      });
    }

  }
};
</script>
<style lang="less">
.dhData {
  // .a-button-blue {
  //   position: absolute;
  //   right: 0;
  //   isIndex: 0;
  // }

}
.orientation-form {
  .ant-radio-button-wrapper {
    border-radius: 40px;
    // overflow: hidden;
    margin: 6px 6px;
    border-left: 1px solid #d9d9d9;
    &::before {
      display: none;
    }
  }

}
.custom-modal {
  .ant-modal-close {
    width: auto !important;
    text-align: right;
    line-height: 56px;
    right: 12px;
    color: #333;
    &:hover {
      color: #1890ff;
    }
  }
  .ant-modal-close-x {
    text-align: right;
    width: 100% !important;
  }
}
</style>
